<template>
  <!-- 创建地图容器 -->
  <div ref="map" style="height:100%">

  </div>
</template>
<script>
import { get } from '@/utils/request'
// 引入辅助函数 
import {mapMutations} from 'vuex';
export default {
  data() {
    return {
      // 存放设备信息
      empData: []
    }
  },
  methods: {
    ...mapMutations(['SET_ED']),
    // 获取设备数据方法
    async getEmp() {
      let res = await get('/dashboard/findEngineerDeviceTree');
      let temp = [];
      res.data.forEach(item => {
        // item -->{id,name,chidlren}
        item.children.forEach(it => {
          // it {id,name,position,设备信息}
          temp.push(it)
        })
      });
      // console.log(temp,'设备数组')
      this.empData = temp;
      this.drawMap();
    },
    // 绘制地图方法
    drawMap() {
      // 2.绘制地图
      var map = new AMap.Map(this.$refs.map, {
        zoom: 11,//缩放级别
        center: [103.839949,36.069335],//中心点坐标
        viewMode: '3D',//使用3D视图
        mapStyle: 'amap://styles/darkblue', //设置地图的显示样式
      });
      // 动态生成标记点
      this.empData.forEach(item => {
        // item --> {id,name,postion,}
        var marker = new AMap.Marker({
          position:item.position,//位置
          icon: 'http://webapi.amap.com/theme/v1.3/markers/b/mark_bs.png',
          title:item.name,
          anchor: 'bottom-left', // 设置锚点方位
          // 标记点携带数据
          extData:item
        })
        // 将组件实例赋值给某一个变量 
        let vm=this;
        marker.on('click', function () {
          // this --->标记点不是组件实例
          // console.log(this.getExtData(), '获取数据');
          vm.SET_ED({
            engineer_id:this.getExtData().engineer_id,
            device_id:this.getExtData().id
          })
        })
        map.add(marker);//添加到地图
      });
      let polygons = [];
      var opts = {
        subdistrict: 0, //获取边界不需要返回下级行政区
        extensions: "all", //返回行政区边界坐标组等具体信息
        level: "district", //查询行政级别为 市
      };
      let district = new AMap.DistrictSearch(opts);
      district.setExtensions("all");
      district.search("兰州市", function (status, result) {
        map.remove(polygons); //清除上次结果
        polygons = [];
        var bounds = result.districtList[0].boundaries;
        if (bounds) {
          for (var i = 0, l = bounds.length; i < l; i++) {
            //生成行政区划polygon
            var polygon = new AMap.Polygon({
              strokeWeight: 5,
              path: bounds[i],
              fillOpacity: 0.4,
              fillColor: "#80d8ff",
              strokeColor: "#0091ea",
            });
            polygons.push(polygon);
          }
        }
        map.add(polygons);
        map.setFitView(polygons); //视口自适应
      });
    }
  },
  mounted() {
    this.getEmp();
    // this.drawMap();
  }
}
</script>
<style>
.amap-icon img {
  width: 24px;
  height: 35px;
}
</style>